<template>
  <div class="doc-container">
    <!-- 文档管理头部 -->
    <div class="doc-header">
      <div class="doc-header-left">
        <n-button quaternary circle size="large" @click="goBack" class="back-button">
          <template #icon>
            <n-icon><ArrowBackOutline /></n-icon>
          </template>
        </n-button>
        <div class="doc-title-section">
          <h1 class="doc-title">{{ knowledgeBaseName || '知识库文档' }}</h1>
          <div class="doc-subtitle">相似度阈值: {{ threshold }}</div>
        </div>
      </div>
      
      <div class="doc-header-actions">
        <n-input-group class="search-group">
          <n-input
            v-model:value="vectorQuery"
            placeholder="向量检索测试..."
            size="large"
            @keydown.enter="handleVectorSearch"
            class="search-input"
          />
          <n-button size="large" type="primary" @click="handleVectorSearch">
            <template #icon>
              <n-icon><SearchOutline /></n-icon>
            </template>
          </n-button>
        </n-input-group>
        
        <n-button type="primary" size="large" @click="goToAddDocument" class="add-button">
          <template #icon>
            <n-icon><AddOutline /></n-icon>
          </template>
          添加文档
        </n-button>
      </div>
    </div>
    
    <!-- 文档列表 - 宫格卡片视图 -->
    <div class="doc-content">
      <div v-if="documents.length === 0 && !loading" class="empty-state">
        <n-empty description="暂无文档" size="large">
          <template #icon>
            <n-icon size="48"><DocumentTextOutline /></n-icon>
          </template>
          <template #extra>
            <n-button size="large" type="primary" @click="goToAddDocument">
              <template #icon>
                <n-icon><AddOutline /></n-icon>
              </template>
              添加第一个文档
            </n-button>
          </template>
        </n-empty>
      </div>
      
      <div v-else class="doc-grid">
        <div v-for="doc in documents" :key="doc.id" class="doc-card" @click="handleViewDocument(doc)">
          <div class="doc-card-icon">
            <n-icon size="32"><DocumentTextOutline /></n-icon>
          </div>
          <div class="doc-card-content">
            <div class="doc-card-title" :title="doc.title || doc.fileName">{{ doc.title || doc.fileName }}</div>
            <div class="doc-card-meta">
              <span class="doc-card-meta-item">
                <n-icon><FolderOutline /></n-icon>
                {{ doc.fileName }}
              </span>
              <span class="doc-card-meta-item">
                <n-icon><ResizeOutline /></n-icon>
                {{ formatFileSize(doc.fileSize || 0) }}
              </span>
            </div>
            <div class="doc-card-meta">
              <span class="doc-card-meta-item">
                <n-icon><TimeOutline /></n-icon>
                {{ formatDateTime(doc.createTime) }}
              </span>
            </div>
          </div>
          <div class="doc-card-status">
            <n-tag
              :type="getStatusType(doc.status)"
              size="small"
              round
            >
              {{ getStatusText(doc.status) }}
            </n-tag>
          </div>
          <div class="doc-card-actions" @click.stop>
            <n-button-group size="small">
              <n-button @click="handleViewDocument(doc)" ghost>
                <template #icon>
                  <n-icon><EyeOutline /></n-icon>
                </template>
              </n-button>
              <n-button @click="handleEditDocument(doc)" type="warning" ghost>
                <template #icon>
                  <n-icon><CreateOutline /></n-icon>
                </template>
              </n-button>
              <n-button @click="handleVersionHistory(doc)" type="info" ghost>
                <template #icon>
                  <n-icon><TimeOutline /></n-icon>
                </template>
              </n-button>
              <n-button @click="handleDeleteDocument(doc)" type="error" ghost>
                <template #icon>
                  <n-icon><TrashOutline /></n-icon>
                </template>
              </n-button>
            </n-button-group>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 向量检索结果 -->
    <transition name="slide-up">
      <div v-if="vectorSearchResult" class="vector-drawer">
        <div class="vector-drawer-header">
          <h3>向量检索结果</h3>
          <n-button quaternary circle size="small" @click="closeVectorOverlay">
            <template #icon>
              <n-icon><CloseOutline /></n-icon>
            </template>
          </n-button>
        </div>
        <div class="vector-drawer-content">
          <div v-if="vectorSearchResult && vectorSearchResult.length">
            <div v-for="(item, idx) in vectorSearchResult" :key="item.id || idx" class="vector-item">
              <div class="vector-item-header">
                <div class="vector-item-index">#{{ idx+1 }}</div>
                <div class="vector-item-score">
                  <n-tag type="warning" size="small">
                    相似度: {{ (item.score ?? item.metadata?.distance ? (1 - item.metadata.distance) : 0).toFixed(3) }}
                  </n-tag>
                </div>
              </div>
              <div class="vector-item-content">{{ item.text }}</div>
            </div>
          </div>
          <div v-else class="vector-empty">
            <n-empty description="无检索结果" />
          </div>
        </div>
      </div>
    </transition>
    
    <!-- 文档查看模态框 -->
    <n-modal v-model:show="viewDialogVisible" class="doc-modal">
      <n-card
        class="doc-modal-card doc-view-modal"
        :title="null"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <template #header>
          <div class="modal-header">
            <n-icon size="24"><EyeOutline /></n-icon>
            <span>文档详情</span>
          </div>
        </template>
        
        <div v-if="currentDocument" class="doc-view-container">
          <div class="doc-view-header">
            <h2 class="doc-view-title">{{ (currentDocument as any).title }}</h2>
            <div class="doc-view-actions">
              <n-button size="small" @click="downloadDocument(currentDocument)">
                <template #icon>
                  <n-icon><DownloadOutline /></n-icon>
                </template>
                下载
              </n-button>
              <n-button size="small" @click="printDocument">
                <template #icon>
                  <n-icon><PrintOutline /></n-icon>
                </template>
                打印
              </n-button>
            </div>
          </div>
          
          <div class="doc-view-content">
            <DocumentPreview 
              :document-url="(currentDocument as any).url || ''"
              :document-name="(currentDocument as any).title || ''"
              :document-content="renderedContent"
              @download="downloadDocument"
              @print="printDocument"
              @share="handleShareDocument"
            />
          </div>
        </div>
        
        <template #footer>
          <div class="modal-footer">
            <n-button @click="viewDialogVisible = false">关闭</n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
    
    <!-- 文档编辑模态框 -->
    <n-modal v-model:show="editDialogVisible" class="doc-modal">
      <n-card
        class="doc-modal-card"
        :title="null"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <template #header>
          <div class="modal-header">
            <n-icon size="24"><CreateOutline /></n-icon>
            <span>编辑文档</span>
          </div>
        </template>
        
        <n-form :model="editForm" :rules="formRules" label-placement="left" label-width="auto" require-mark-placement="right-hanging">
          <n-form-item label="文档标题" path="title">
            <n-input v-model:value="editForm.title" placeholder="请输入文档标题" />
          </n-form-item>
          <n-form-item label="文档内容" path="content">
            <div class="text-input-container">
              <n-input
                v-model:value="editForm.content"
                type="textarea"
                placeholder="请输入文档内容（纯文本格式）"
                :autosize="{ minRows: 8, maxRows: 15 }"
                @input="updateEditMarkdownPreview"
              />
              <div class="markdown-preview-section">
                <div class="preview-header">
                  <n-icon><EyeOutline /></n-icon>
                  <span>Markdown预览</span>
                </div>
                <div class="markdown-preview" v-html="editMarkdownPreview"></div>
              </div>
            </div>
          </n-form-item>
        </n-form>
        
        <template #footer>
          <div class="modal-footer">
            <n-button @click="editDialogVisible = false">取消</n-button>
            <n-button type="primary" @click="saveEdit" :loading="uploading">
              <template #icon>
                <n-icon><CheckmarkOutline /></n-icon>
              </template>
              保存
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
    
    <!-- 图片预览模态框 -->
    <n-modal v-model:show="imagePreviewVisible" class="image-preview-modal">
      <n-card
        class="image-preview-card"
        :title="null"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <div class="image-preview-container">
          <img :src="previewImageUrl" alt="图片预览" class="preview-image" />
        </div>
        
        <template #footer>
          <div class="modal-footer">
            <n-button @click="imagePreviewVisible = false">关闭</n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
    
    <!-- 文档分享模态框 -->
    <n-modal
      v-model:show="shareDialogVisible"
      preset="card"
      style="width: 500px"
      title="分享文档"
      :bordered="false"
      :closable="true"
      :auto-focus="false"
    >
      <div v-if="shareDocument" class="share-content">
        <div class="share-document-info">
          <div class="share-document-title">{{ shareDocument.title }}</div>
          <div class="share-document-meta">
            <span>文件名: {{ shareDocument.fileName }}</span>
            <span>大小: {{ formatFileSize(shareDocument.fileSize) }}</span>
          </div>
        </div>
        
        <n-divider />
        
        <div class="share-link-section">
          <div class="share-link-header">
            <n-icon><LinkOutline /></n-icon>
            <span>分享链接</span>
          </div>
          <div class="share-link-input">
            <n-input
              v-model:value="shareUrl"
              readonly
              placeholder="分享链接"
            />
            <n-button
              type="primary"
              :disabled="shareCopied"
              @click="copyShareUrl"
            >
              {{ shareCopied ? '已复制' : '复制链接' }}
            </n-button>
          </div>
        </div>
        
        <div class="share-options">
          <div class="share-option-item">
            <n-icon><QrCodeOutline /></n-icon>
            <span>二维码分享</span>
            <n-button size="small" @click="generateQRCode">
              生成二维码
            </n-button>
          </div>
          
          <div class="share-option-item">
            <n-icon><MailOutline /></n-icon>
            <span>邮件分享</span>
            <n-button size="small" @click="shareViaEmail">
              发送邮件
            </n-button>
          </div>
        </div>
        
        <div class="share-tips">
          <n-alert type="info" :closable="false">
            任何人都可以通过此链接访问文档，请谨慎分享。
          </n-alert>
        </div>
      </div>
      
      <template #footer>
        <div style="display: flex; justify-content: flex-end;">
          <n-button @click="shareDialogVisible = false">
            关闭
          </n-button>
        </div>
      </template>
    </n-modal>
    
    <!-- 文档版本历史模态框 -->
    <n-modal v-model:show="versionDialogVisible" class="doc-modal">
      <n-card
        class="doc-modal-card"
        :title="null"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <template #header>
          <div class="modal-header">
            <n-icon size="24"><TimeOutline /></n-icon>
            <span>版本历史</span>
          </div>
        </template>
        
        <DocumentVersionManager 
          v-if="currentDocument"
          :document-id="(currentDocument as any).id"
          :document-title="(currentDocument as any).title"
          @restore="handleRestoreVersion"
          @compare="handleCompareVersions"
        />
        
        <template #footer>
          <div class="modal-footer">
            <n-button @click="versionDialogVisible = false">关闭</n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NIcon, useMessage, NInput, NModal, NFormItem, NForm } from 'naive-ui'
import { AddOutline, SearchOutline, ArrowBackOutline, CloseOutline, DownloadOutline, PrintOutline, FolderOutline, ResizeOutline, TimeOutline, LinkOutline, QrCodeOutline, MailOutline, EyeOutline, CreateOutline, TrashOutline, DocumentTextOutline, CheckmarkOutline } from '@vicons/ionicons5'
import { aiService } from '../../shared/services/ai-service'  
import DocumentPreview from '../components/DocumentPreview.vue'
import DocumentVersionManager from '../components/DocumentVersionManager.vue'
import '@/styles/KnowledgeDocument.css'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const documents = ref<any[]>([])
const loading = ref(false)
const page = ref(1) // 固定为第一页
const pageSize = ref(100) // 固定为100
const total = ref(0)
const pollingInterval = ref<NodeJS.Timeout|null>(null)

const knowledgeBaseName = ref('')
const vectorQuery = ref('')
const threshold = ref(parseFloat(route.query.threshold as string) || 0.7)
const vectorSearchResult = ref<any[]|null>(null)

// 文档查看和编辑相关状态
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentDocument = ref(null)
const editForm = reactive({
  id: '',
  title: '',
  content: '',
  knowledgeBaseId: ''
})

// 文档分享相关状态
const shareDialogVisible = ref(false)
const shareDocument = ref<any>(null)
const shareUrl = ref('')
const shareCopied = ref(false)

// 文档版本历史相关状态
const versionDialogVisible = ref(false)
const versionHistory = ref<any[]>([])
const versionLoading = ref(false)
const comparingVersions = ref(false)
const selectedVersions = ref<any[]>([])

// 文档解析相关状态
const renderedContent = ref('')
const tableOfContents = ref([])
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')

// 表单验证规则
const formRules = {
  title: {
    required: true,
    message: '请输入文档标题',
    trigger: ['input', 'blur']
  },
  content: {
    required: true,
    message: '请输入文档内容',
    trigger: ['input', 'blur']
  }
}

// 编辑相关状态
const uploading = ref(false)
const editMarkdownPreview = ref<string>('')

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期时间
function formatDateTime(dateString: string): string {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取文档状态类型
function getStatusType(status: number): string {
  const statusMap: any = {
    1: 'success',
    0: 'error',
    2: 'warning'
  }
  return statusMap[status] || 'default'
}

// 获取文档状态文本
function getStatusText(status: number): string {
  const statusMap: any = {
    1: '正常',
    0: '已删除',
    2: '处理中'
  }
  return statusMap[status] || '未知'
}

// 轮询处理
function startPollingIfNeeded() {
  stopPolling()
  if (documents.value.some(doc => (doc.progress ?? 100) < 100)) {
    pollingInterval.value = setInterval(() => {
      loadDocuments(true)
    }, 1000)
  }
}

function stopPolling() {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value)
    pollingInterval.value = null
  }
}

// 加载文档列表
async function loadDocuments(isPolling = false) {
  const knowledgeId = route.params.knowledgeId as string
  if (!knowledgeId) return
  if (!isPolling) loading.value = true
  try {
    const res = await aiService.getKnowledgeDocuments(knowledgeId, page.value, pageSize.value)
    // 后端返回的数据结构是 {code: 0, msg: "success", data: {total, current, pages, size, records}}
    // @ts-ignore
    if (res && (res as any).code === 0 && (res as any).data) {
      // @ts-ignore
      documents.value = (res as any).data.records || []
      // @ts-ignore
      total.value = (res as any).data.total || 0
    } else {
      documents.value = []
      total.value = 0
    }
    startPollingIfNeeded()
  } catch (e) {
    message.error('加载文件失败')
    stopPolling()
  } finally {
    if (!isPolling) loading.value = false
  }
}

// 返回知识库列表
function goBack() {
  router.push('/kb')
}

// 跳转到添加文档页面
function goToAddDocument() {
  const knowledgeId = route.params.knowledgeId as string
  router.push({
    path: `/knowledge/${knowledgeId}/add-document`,
    query: {
      kbName: knowledgeBaseName.value
    }
  })
}

// 向量检索
async function handleVectorSearch() {
  const query = vectorQuery.value.trim()
  const knowledgeId = route.params.knowledgeId as string
  if (!query || !knowledgeId) return
  try {
    // @ts-ignore
    const res = await (vectorQuery as any)(query, knowledgeId, threshold.value)
    // @ts-ignore
    if ((res as any).success && Array.isArray((res as any).data)) {
      // @ts-ignore
      vectorSearchResult.value = (res as any).data
      // 直接显示浮层
    } else {
      // @ts-ignore
      message.error((res as any).message || '检索失败')
    }
  } catch (e) {
    message.error('检索失败')
  }
}

function closeVectorOverlay() {
  vectorSearchResult.value = null
}

// 查看文档
async function handleViewDocument(doc: any) {
  try {
    const res = await aiService.getDocumentById(doc.id)
    
    // 处理API响应数据结构兼容性
    // @ts-ignore
    const isSuccess = (res as any).success || res.code === 200
    // @ts-ignore
    const docData = (res as any).data || res
    
    if (isSuccess && docData) {
      currentDocument.value = docData
      viewDialogVisible.value = true
      // 解析文档内容
      nextTick(() => {
        parseDocumentContent(docData.content || '')
      })
    } else {
      // @ts-ignore
      message.error((res as any).message || '获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情失败:', error);
    message.error('获取文档详情失败')
  }
}

// 编辑文档
async function handleEditDocument(row: any) {
  try {
    const res = await aiService.getDocumentById(row.id)
    // 处理API返回的数据结构，可能是 {success: true, data: {...}} 或 {code: 200, data: {...}}
    // @ts-ignore
    const isSuccess = (res as any).success || res.code === 200
    // @ts-ignore
    const docData = (res as any).data || res
    
    if (isSuccess && docData) {
      Object.assign(editForm, {
        id: docData.id,
        title: docData.title,
        content: docData.content,
        knowledgeBaseId: docData.knowledgeBaseId
      })
      // 初始化编辑模式的Markdown预览
      updateEditMarkdownPreview()
      editDialogVisible.value = true
    } else {
      // @ts-ignore
      message.error((res as any).message || '获取文档详情失败')
    }
  } catch (e) {
    console.error('获取文档详情失败:', e);
    message.error('获取文档详情失败')
  }
}

// 更新编辑模式的Markdown预览
function updateEditMarkdownPreview() {
  if (editForm.content) {
    editMarkdownPreview.value = renderMarkdown(editForm.content)
  } else {
    editMarkdownPreview.value = ''
  }
}

// 简单的Markdown渲染函数
function renderMarkdown(content: string): string {
  return content
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/`(.+?)`/g, '<code>$1</code>')
    .replace(/\n\n/g, '</p><p>')
    .replace(/^\s*(.+?)\s*$/gm, '<p>$1</p>')
    .replace(/<p><\/p>/g, '')
    .replace(/<p>(<h[1-6]>)/g, '$1')
    .replace(/(<\/h[1-6]>)<\/p>/g, '$1')
}

// 保存编辑
async function saveEdit() {
  if (!editForm.title || !editForm.content) {
    message.error('标题和内容不能为空')
    return
  }
  
  try {
    const res = await aiService.updateDocument(editForm.id, editForm)
    // 处理API返回的数据结构，可能是 {success: true, data: {...}} 或 {code: 200, data: {...}}
    // @ts-ignore
    const isSuccess = (res as any).success || res.code === 200
    
    if (isSuccess) {
      message.success('文档更新成功')
      editDialogVisible.value = false
      // 刷新文档列表
      loadDocuments()
    } else {
      // @ts-ignore
      message.error((res as any).message || '更新文档失败')
    }
  } catch (e) {
    console.error('更新文档失败:', e);
    message.error('更新文档失败')
  }
}

// 删除文档
async function handleDeleteDocument(row: any) {
  const knowledgeId = route.params.knowledgeId as string
  if (!knowledgeId || !row.id) return
  
  // 确认删除
  if (!confirm(`确定要删除文档"${row.title || row.fileName}"吗？`)) {
    return
  }
  
  try {
    const res = await aiService.deleteDocument(row.id)
    // @ts-ignore
    if ((res as any).success) {
      message.success('删除成功')
      loadDocuments()
    } else {
      // @ts-ignore
      message.error((res as any).message || '删除失败')
    }
  } catch (e) {
    message.error('删除失败')
  }
}

// 解析文档内容
function parseDocumentContent(content: any) {
  try {
    if (!content) {
      renderedContent.value = '<div class="empty-content"><p>暂无内容</p></div>'
      // @ts-ignore
      tableOfContents.value = []
      return
    }
    
    // 提取标题生成目录
    extractTableOfContents(content)
    
    // 渲染内容
    renderDocumentContent(content)
    
    // 处理图片预览
    processImagePreview(content)
  } catch (error: any) {
    console.error('解析文档内容失败:', error);
    // @ts-ignore
    renderedContent.value = `<div class="error-content"><p>文档内容解析失败: ${error.message}</p></div>`
    // @ts-ignore
    tableOfContents.value = []
  }
}

// 提取文档目录
function extractTableOfContents(content: any) {
  const toc: any[] = []
  const headingRegex = /^(#{1,6})\s+(.+)$/gm
  let match
  
  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length
    const text = match[2].trim()
    // @ts-ignore
    const id: any = `heading-${toc.length}`
    
    toc.push({
      level,
      text,
      id
    })
  }
  
  // @ts-ignore
  tableOfContents.value = toc
}

// 处理图片预览
function processImagePreview(_content: any) {
  // 这个函数将在DOM更新后调用
  nextTick(() => {
    try {
      const images = document.querySelectorAll('#document-content img')
      images.forEach((img: any) => {
        // 移除之前的事件监听器，避免重复添加
        img.removeEventListener('click', handleImageClick)
        // 添加新的事件监听器
        img.addEventListener('click', handleImageClick)
        // 设置样式
        img.style.cursor = 'pointer'
        img.style.maxWidth = '100%'
      })
    } catch (error) {
      console.error('处理图片预览失败:', error);
    }
  })
}

// 图片点击处理函数
function handleImageClick(event: any) {
  const img = event.target
  if (img && img.src) {
    previewImageUrl.value = img.src
    imagePreviewVisible.value = true
  }
}

// 渲染文档内容
function renderDocumentContent(content: any) {
  // 简单的Markdown渲染
  let html = content
    // 处理标题
    .replace(/^(#{1,6})\s+(.+)$/gm, (_match: any, hashes: any, text: any) => {
      const level = hashes.length
      // @ts-ignore
      const index = Array.from(tableOfContents.value).findIndex((item: any) => item.text === text.trim())
      // @ts-ignore
      const id = index >= 0 ? tableOfContents.value[index].id : `heading-${Math.random().toString(36).substr(2, 9)}`
      return `<h${level} id="${id}">${text}</h${level}>`
    })
    // 处理粗体
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    // 处理斜体
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    // 处理删除线
    .replace(/~~(.+?)~~/g, '<del>$1</del>')
    // 处理代码块
    .replace(/```([\s\S]*?)```/g, '<pre class="code-block"><code>$1</code></pre>')
    // 处理行内代码
    .replace(/`(.+?)`/g, '<code class="inline-code">$1</code>')
    // 处理链接
    .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
    // 处理图片
    .replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" class="document-image" />')
    // 处理引用块
    .replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>')
    // 处理表格 - 先处理表格行
    .replace(/^\|(.+)\|$/gm, (_match: any, content: any) => {
      const cells = content.split('|').map((cell: any) => cell.trim())
      const cellTags = cells.map((cell: any) => `<td>${cell}</td>`).join('')
      return `<tr>${cellTags}</tr>`
    })
    // 处理表格分隔符
    .replace(/^\|[\s\-\|:]+\|$/gm, '')
    // 将表格行包装在表格标签中
    .replace(/(<tr>.*<\/tr>)(\s*<tr>.*<\/tr>)*/gs, (match: any) => {
      return `<table class="document-table">${match}</table>`
    })
    // 处理无序列表
    .replace(/^[\*\-\+]\s+(.+)$/gm, '<li>$1</li>')
    // 将连续的列表项包装在ul标签中
    .replace(/(<li>.*<\/li>)(\s*<li>.*<\/li>)*/gm, (match: any) => {
      return `<ul class="document-list">${match}</ul>`
    })
    // 处理有序列表
    .replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>')
    // 处理换行
    .replace(/\n\n/g, '</p><p>')
    .replace(/\n/g, '<br>')
  
  // 包装在段落标签中
  html = `<div class="document-content">${html}</div>`
  
  renderedContent.value = html
}

// 下载文档
function downloadDocument(doc = null) {
  const documentToDownload = doc || currentDocument.value
  if (!documentToDownload) return
  
  try {
    // 创建一个包含文档内容的Blob
    // @ts-ignore
    const content = (documentToDownload as any).content || ''
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    
    // 创建临时下载链接
    const link = document.createElement('a')
    link.href = url
    // @ts-ignore
    link.download = (documentToDownload as any).fileName || (documentToDownload as any).title + '.txt'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 释放URL对象
    URL.revokeObjectURL(url)
    
    message.success('文档下载已开始')
  } catch (error) {
    console.error('下载文档失败:', error);
    message.error('下载文档失败')
  }
}

// 打印文档
function printDocument() {
  if (!currentDocument.value) return
  
  window.print()
}

// 分享文档
function handleShareDocument(document: any) {
  shareDocument.value = document
  shareUrl.value = `${window.location.origin}/knowledge/${route.params.knowledgeId}/document/${document.id}`
  shareDialogVisible.value = true
  shareCopied.value = false
}

// 复制分享链接
async function copyShareUrl() {
  try {
    await navigator.clipboard.writeText(shareUrl.value)
    shareCopied.value = true
    message.success('链接已复制到剪贴板')
    setTimeout(() => {
      shareCopied.value = false
    }, 2000)
  } catch (error) {
    console.error('复制链接失败:', error);
    message.error('复制链接失败，请手动复制')
  }
}

// 生成分享二维码
function generateQRCode() {
  // 这里可以集成二维码生成库
  message.info('二维码生成功能待实现')
}

// 邮件分享
function shareViaEmail() {
  const subject = encodeURIComponent(`分享文档: ${shareDocument.value?.title}`)
  const body = encodeURIComponent(`我想与您分享这个文档: ${shareUrl.value}`)
  window.open(`mailto:?subject=${subject}&body=${body}`)
}

// 版本历史相关方法
function handleVersionHistory(doc: any) {
  currentDocument.value = doc
  versionDialogVisible.value = true
  loadVersionHistory(doc.id)
}

// 加载版本历史
async function loadVersionHistory(documentId: string) {
  if (!documentId) return
  
  versionLoading.value = true
  try {
    // 这里应该调用实际的API获取版本历史
    // const res = await aiService.getDocumentVersions(documentId)
    
    // 模拟版本历史数据
    const mockVersions = [
      {
        id: 'v1',
        version: '1.0',
        createTime: '2023-10-15 10:30:00',
        creator: '张三',
        changeDescription: '初始版本',
        content: '这是文档的初始内容...'
      },
      {
        id: 'v2',
        version: '1.1',
        createTime: '2023-10-16 14:20:00',
        creator: '李四',
        changeDescription: '添加了第二章内容',
        content: '这是文档的更新内容...'
      },
      {
        id: 'v3',
        version: '1.2',
        createTime: '2023-10-17 09:15:00',
        creator: '王五',
        changeDescription: '修复了格式问题',
        content: '这是文档的最新内容...'
      }
    ]
    
    versionHistory.value = mockVersions
  } catch (error) {
    console.error('加载版本历史失败:', error);
    message.error('加载版本历史失败')
  } finally {
    versionLoading.value = false
  }
}

// 恢复版本
async function handleRestoreVersion(versionId: string) {
  if (!versionId || !currentDocument.value) return
  
  try {
    // 这里应该调用实际的API恢复版本
    // const res = await aiService.restoreDocumentVersion(currentDocument.value.id, versionId)
    
    message.success('版本恢复成功')
    versionDialogVisible.value = false
    loadDocuments() // 刷新文档列表
  } catch (error) {
    console.error('恢复版本失败:', error);
    message.error('恢复版本失败')
  }
}

// 比较版本
function handleCompareVersions(version1: any, version2: any) {
  if (!version1 || !version2) return
  
  selectedVersions.value = [version1, version2]
  comparingVersions.value = true
  
  // 这里可以打开版本比较模态框或页面
  message.info('版本比较功能待实现')
}

// 页面初始化
onMounted(() => {
  knowledgeBaseName.value = route.query.kbName as string || ''
  loadDocuments()
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  try {
    // 清理图片点击事件监听器
    const images = document.querySelectorAll('#document-content img')
    images.forEach(img => {
      img.removeEventListener('click', handleImageClick)
    })
  } catch (error) {
    console.error('清理事件监听器失败:', error)
  }
  
  // 停止轮询
  stopPolling()
})

// 页面卸载时清理轮询
defineExpose({ stopPolling })
</script>
